<template>
  <div class="shop-cart">
    <div class="content" @click="toggleCartList">
      <div class="icon" :class="{'is-select':totalCount > 0}">
        <i class="icon-shopping_cart"></i>
        <bubble v-show="totalCount" :num="totalCount"></bubble>
      </div>
      <div class="info">
        <div class="price">￥{{totalPrice}}</div>
        <div class="line"></div>
        <div class="min-price">另需配送费￥{{deliveryPrice}}元</div>
      </div>
      <div class="pay" @click.stop="pay" :class="enoughPayCls">{{enoughPayText}}</div>
    </div>
    <div class="ball-container">
      <div v-for="(ball, index) in balls" :key="index">
        <transition @before-enter="beforeDrop" @enter="dropping" @after-enter="afterDrop">
          <div v-show="ball.show" class="ball">
            <div class="inner inner-hook"></div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>
<script>
import Bubble from '../bubble/bubble.vue'

const BALL_LEN = 10

function creatBalls() {
  let ret = []
  for (let i = 0; i < BALL_LEN; i++) {
    ret.push({
      show: false
    })
  }
  return ret
}

export default {
  name: 'shop-cart',
  props: {
    // 最低起送费
    minPrice: {
      type: Number,
      default: 0
    },

    // 配送费
    deliveryPrice: {
      type: Number,
      default: 0
    },

    // 已选商品
    selectedFoods: {
      type: Array,
      default() {
        return []
      }
    },
    fold: {
      type: Boolean,
      default: true
    },
    sticky: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      balls: creatBalls(),
      listFold: this.fold
    }
  },
  computed: {
    // 已选择商品总数量
    totalCount() {
      let count = 0
      this.selectedFoods.forEach((selectedFood) => {
        count += selectedFood.count
      })
      return count
    },
    totalPrice() {
      let price = 0
      this.selectedFoods.forEach((selectedFood) => {
        price += selectedFood.price * selectedFood.count
      })
      return price
    },
    enoughPayCls() {
      if (this.totalPrice >= this.minPrice) {
        return 'enough'
      } else {
        return 'un-enough'
      }
    },
    enoughPayText() {
      if (this.totalPrice === 0) {
        return `${this.minPrice}起送`
      }
      if (this.totalPrice < this.minPrice) {
        return `差${this.minPrice - this.totalPrice}元起送`
      } else {
        return '付款'
      }
    }
  },
  created() {
    this.dropBalls = []
  },
  methods: {
    drop(el) {
      for (let i = 0; i < this.balls.length; i++) {
        const ball = this.balls[i]
        if (!ball.show) {
          ball.show = true
          ball.el = el
          this.dropBalls.push(ball)
          return
        }
      }
    },
    beforeDrop(el) {
      /**
         * 小球初始位置
         * 即按钮的位置
         * */
      // 取出最后一个小球
      const ball = this.dropBalls[this.dropBalls.length - 1]
      // 使用 DOM 的api获取元素的位置信息
      const rect = ball.el.getBoundingClientRect()
      // 32 是购物车上小球距离左边的距离，x是小球需要移动的x轴距离
      const x = rect.left - 32
      // 22 是购物车上小球距离底部的距离
      const y = -(window.innerHeight - rect.top - 22)
      el.style.display = ''
      el.style.transform = el.style.webkitTransform = `translate3d(0, ${y}px, 0)`
      const inner = el.getElementsByClassName('inner-hook')[0]
      inner.style.transform = inner.style.webkitTransform = `translate3d(${x}px, 0, 0)`
    },
    dropping(el, done) {
      /**
         * 动画结束小球的位置
         * 即小球本身的位置
         * */
      // 触发重绘，transition内部是这样实现的
      this._reflow = document.body.offsetHeight
      el.style.transform = el.style.webkitTransform = `translate3d(0, 0, 0)`
      const inner = el.getElementsByClassName('inner-hook')[0]
      inner.style.transform = inner.style.webkitTransform = `translate3d(0, 0, 0)`
      el.addEventListener('transitionend', done)
    },
    afterDrop(el) {
      // 取出第一个小球
      const ball = this.dropBalls.shift()
      if (ball.show) {
        ball.show = false
        el.style.display = 'none'
      }
    },
    toggleCartList() {
      if (this.listFold) {
        if (!this.totalCount) {
          return
        }
        this.listFold = false
        this._showShopCartList()
        this._showShopCartSticky()
      } else {
        this.listFold = true
        this._hideShopCartList()
      }
    },
    _showShopCartList() {
      this.shopCartListComp = this.shopCartListComp || this.$createShopCartList({
        $props: {
          selectFoods: 'selectedFoods'
        },
        $events: {
          hide: () => {
            this.listFold = true
          },
          leave: () => {
            this._hideShopCartSticky()
          },
          add: (el) => {
            this.shopCartStickyComp.drop(el)
          }
        }
      })
      this.shopCartListComp.show()
    },
    _showShopCartSticky() {
      this.shopCartStickyComp = this.shopCartStickyComp || this.$createShopCartSticky({
        $props: {
          minPrice: 'minPrice',
          deliveryPrice: 'deliveryPrice',
          selectedFoods: 'selectedFoods',
          fold: 'listFold',
          list: this.shopCartListComp
        }
      })
      this.shopCartStickyComp.show()
    },
    _hideShopCartList() {
      const list = this.sticky ? this.$parent.list : this.shopCartListComp
      list.hide && list.hide()
    },
    _hideShopCartSticky() {
      this.shopCartStickyComp.hide()
    },
    pay(e) {
      if (this.totalPrice < this.minPrice) {
        return
      }
      this.$createDialog({
        type: 'alert',
        title: '支付',
        content: `您共需要支付${this.totalPrice}`
      }).show()
      e.stopPropagation()
    }
  },
  watch: {
    fold(newVal) {
      this.listFold = newVal
    },
    totalCount(newVal) {
      if (!this.listFold && !newVal) {
        this._hideShopCartList()
      }
    }
  },
  components: {
    Bubble
  }
}
</script>
<style lang="stylus" scoped>
@import '../../common/stylus/variable.styl'
@import '../../common/stylus/mixin.styl'

.shop-cart
  height 48px
  background #131d26
  .content
    display flex
    justify-content space-between
    .icon
      z-index 9
      position relative
      top -10px
      margin-left 18px
      line-height 44px
      width 38px
      height 38px
      background #2b343c
      border-radius 50%
      text-align center
      border solid 6px #141d27
      .icon-shopping_cart
        font-size $fontsize-large-xxx
        color #80858a
      &.is-select
        background $color-blue
        .icon-shopping_cart
          color $color-white
      .bubble
        position absolute
        top -4px
        left 20px
    .info
      display flex
      flex 1
      overflow hidden
      align-items center
      padding 0 18px
      .price
        line-height 24px
        font-size $fontsize-large-x
        font-weight 700
        color $color-text-ss
      .line
        height 30px
        margin 0 12px
        border-1px($color = rgba(255, 255, 255, 0.1))
      .min-price
        line-height 24px
        font-size $fontsize-small
        font-weight 700
        color rgba(255, 255, 255, 0.4)
        truncate()
    .pay
      width 105px
      height 48px
      line-height 48px
      text-align center
      font-size $fontsize-medium
      font-weight 700
      &.un-enough
        background #2b343c
        color rgba(255, 255, 255, 0.4)
      &.enough
        background $color-green
        color $color-white
  .ball-container
    .ball
      position fixed
      left 34px
      bottom 28px
      z-index 200
      transition all 0.4s cubic-bezier(0.49, -0.29, 0.75, 0.41)
      .inner
        width 16px
        height 16px
        border-radius 50%
        background $color-blue
        transition all 0.4s linear
</style>
